package club.ljwang.wechat;

import club.ljwang.constant.RedisMessageConstant;
import club.ljwang.entity.Result;
import club.ljwang.pojo.Order;
import club.ljwang.pojo.OrderInfo;
import club.ljwang.service.OrderService;
import club.ljwang.utils.JedisUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: wangl
 * @Date: 2020/3/4 00:35
 * @Description:
 */

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private JedisUtil jedisUtil;

    @Reference
    private OrderService orderService;


    @RequestMapping("submit")
    public Result submit(@RequestBody OrderInfo orderInfo) {
        String telephone = orderInfo.getTelephone();
        String validateCode = orderInfo.getValidateCode();
        String token = orderInfo.getToken();
        if (token == null) {
            return new Result(false, "非法请求!");
        }
        Long delete = jedisUtil.delete(token);

        if (delete == 0L) {
            return new Result(false, "非法请求!");
        }
        String redisCode = jedisUtil.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);


        if (validateCode == null || !validateCode.equals(redisCode)) {
            jedisUtil.setex(token, 60 * 60 * 2, token);
            return new Result(false, "验证码校验失败!");

        }
        orderInfo.setOrderType(Order.ORDERTYPE_WEIXIN);
        Result result = null;

        int max = 15;
        while (max > 0) {
            try {
                result = orderService.submit(orderInfo);
                return  result;
            } catch (OptimisticLockingFailureException e) {
                e.printStackTrace();
                max --;

                if(max==0){
                    System.out.println("重试"+max+"次还不行：" + JSON.toJSONString(orderInfo));
                }
            }
        }

        return result;

    }

    @RequestMapping("findById")
    public Result findById(Integer id) {

        return orderService.findById(id);

    }


}
